//将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 
//
// 示例： 
//
// 输入：1->2->4, 1->3->4
//输出：1->1->2->3->4->4
// 
// Related Topics 链表


package leetcode.d_1_99;

//Java：合并两个有序链表
public class P21MergeTwoSortedLists{
    public static void main(String[] args) {
        Solution solution = new P21MergeTwoSortedLists().new Solution();
        // TO TEST
    }
    //leetcode submit region begin(Prohibit modification and deletion)
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */

//    class Solution {
//        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
//            if (l1 == null){
//                return l2;
//            }
//            if (l2 == null){
//                return l1;
//            }
//            ListNode pMergeHead = null;
//            if (l1.val < l2.val){
//                pMergeHead = l1;
//                pMergeHead.next = mergeTwoLists(l1.next, l2);
//            }else {
//                pMergeHead = l2;
//                pMergeHead.next = mergeTwoLists(l1, l2.next);
//            }
//            return pMergeHead;
//        }
//    }

    class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            ListNode node = new ListNode(-1);
            ListNode res = node;
            while (l1 != null && l2 != null){
                if (l1.val < l2.val){
                    res.next = l1;
                    l1 = l1.next;
                }else {
                    res.next = l2;
                    l2 = l2.next;
                }
                res = res.next;
            }
            //剩下的链表是有序的
            res.next = (l1 == null) ? l2 : l1;
            return node.next;
        }

        // 递归写法
        public ListNode mergeTwoLists2(ListNode list1, ListNode list2) {
            if (list1 == null) {
                return list2;
            }
            if (list2 == null) {
                return list1;
            }
            if (list1.val < list2.val) {
                list1.next = mergeTwoLists2(list1.next, list2);
                return list1;
            }else {
                list2.next = mergeTwoLists2(list2.next, list1);
                return list2;
            }
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}